package com.example.usermanager.controller;

import com.example.usermanager.model.UserInfo;
import com.example.usermanager.service.UserService;
import com.example.usermanager.util.ConstVariable;;
import com.example.usermanager.util.PassWordUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author 郝文雪
 * @date 2022/8/6 10:00
 * @Description Test
 */
@RestController
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 用户登录
     * @param request
     * @param loginname
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public boolean login(HttpServletRequest request,String loginname, String password){
        if(StringUtils.hasLength(loginname) && StringUtils.hasLength(password)){
            //参数有效
            UserInfo userInfo = userService.getUserByLoginName(loginname);
            if(userInfo!=null && userInfo.getUid()>0 && userInfo.isIsadmin()) {
                //数据库保存的加密的密码
                String dbPassword=userInfo.getPassword();
                boolean result= PassWordUtil.decrypt(password,dbPassword);
                if(result) {
                    //存储session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(ConstVariable.USER_SESSION_KEY, userInfo);
                    return true;
                }
            }

        }
        return false;
    }

    /**
     * 查询所有列表（无分页）
     * @return
     */
    @RequestMapping("/list")
    public List<UserInfo> getAll(){
        return userService.getAll();
    }

    @RequestMapping("/listbypage")
    public HashMap<String,Object> getListByPage(String username,
                                                String address,
                                                String email,
                                                Integer pindex,
                                                Integer psize){
        HashMap<String,Object> map=new HashMap<>();
        if(pindex==null || pindex<1){
            pindex=1;
        }
        if(psize==null || psize<0){
            psize=2;
        }
        if(!StringUtils.hasLength(username)){
            username=null;
        }
        if(!StringUtils.hasLength(address)){
            address=null;
        }
        if(!StringUtils.hasLength(email)){
            email=null;
        }
        int offset=(pindex-1)*psize;
        List<UserInfo> list= userService.getListByPage(username,address,email,psize,offset);
        int total=userService.totalCount(username,address,email);
        map.put("list",list);
        map.put("count",total);
        return map;
    }


    /**
     * 添加用户
     * @param userInfo
     * @param request
     * @return
     */
    @RequestMapping("/add")
    public int add(UserInfo userInfo,HttpServletRequest request){
        int result=0;
        //1.非空校验
        if(userInfo==null || !StringUtils.hasLength(userInfo.getUsername())
        || !StringUtils.hasLength(userInfo.getLoginname())
        || !StringUtils.hasLength(userInfo.getPassword())) return result;
        //2.判断必须为超级管理员才能进行添加操作
        HttpSession session=request.getSession(false);
        if(session==null || session.getAttribute(ConstVariable.USER_SESSION_KEY)==null) return result;
        UserInfo loginUser=(UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if(!loginUser.isIsadmin()) return result;
        //3.对登录名做唯一校验
        UserInfo userByLoginName = userService.getUserByLoginName(userInfo.getLoginname());
        if(userByLoginName!=null && userByLoginName.getUid()>0) return result;
        //4.添加用户到数据库
        String password=userInfo.getPassword();
        userInfo.setPassword(PassWordUtil.encrypt(password));
        result= userService.add(userInfo);
        return result;
    }

    /**
     * 根据uid查询用户的信息
     * @param uid
     * @return
     */
    @RequestMapping("/getuserbyuid")
    public UserInfo getUserByUid(Integer uid){
        UserInfo userInfo=null;
        //1.非空校验
        if(uid!=null && uid>0){
             userInfo= userService.getUserByUid(uid);
             userInfo.setPassword("");
        }
        return userInfo;
    }

    /**
     * 修改用户信息
     * @param userInfo
     * @return
     */
    @RequestMapping("/updateuser")
    public int updateUser(UserInfo userInfo,HttpServletRequest request){
        int result=0;
        //1.非空校验
        if(userInfo==null || userInfo.getUid()<=0 || !StringUtils.hasLength(userInfo.getUsername())) return result;
        //2.判断必须为超级管理员才能进行添加操作
        HttpSession session=request.getSession(false);
        if(session==null || session.getAttribute(ConstVariable.USER_SESSION_KEY)==null) return result;
        UserInfo loginUser=(UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if(!loginUser.isIsadmin()) return result;
        //3.执行修改操作
        if(StringUtils.hasLength(userInfo.getPassword())){
            userInfo.setPassword(PassWordUtil.encrypt(userInfo.getPassword()));
        }else{
            userInfo.setPassword(null);
        }
        result= userService.updateUser(userInfo);
        return result;
    }

    /**
     * 删除单条用户信息
     * @param uid
     * @param request
     * @return
     */
    @RequestMapping("/deluser")
    public int delUser(Integer uid,HttpServletRequest request){
        int result=0;
        //1.非空校验
        if(uid==null || uid<=0) return result;
        //2.判断是否超级管理员
        HttpSession session=request.getSession(false);
        UserInfo userInfo=(UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if(!userInfo.isIsadmin()) return result;
        result=userService.delUser(uid);
        return result;
    }


    /**
     * 删除选中用户的信息
     * @param ids
     * @param request
     * @return
     */
    @RequestMapping("/delbyids")
    public int delByIds(String ids,HttpServletRequest request){
        if(!StringUtils.hasLength(ids)) return 0;
        String[] idsArr=ids.split(",");
        if(idsArr==null || idsArr.length<=0) return 0;
        List<Integer> idsList=new ArrayList<>();
        HttpSession session=request.getSession(false);
        if(session==null || session.getAttribute(ConstVariable.USER_SESSION_KEY)==null) return 0;
        int uid=((UserInfo)session.getAttribute(ConstVariable.USER_SESSION_KEY)).getUid();
        for(String item:idsArr){
            if(StringUtils.hasLength(item)){
                int thisuid=Integer.valueOf(item);
                //删除之前，判断不是删除自己
                if(uid==thisuid) return 0;
                idsList.add(thisuid);
            }
        }
        int result= userService.delByIds(idsList);
        return result;

    }
}
